package com.ruoyi.article.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.article.domain.Category;
import com.ruoyi.utils.FileUtils;
import com.ruoyi.web.model.AppResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.article.domain.SysArticle;
import com.ruoyi.article.service.ISysArticleService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 博客文章Controller
 * 
 * @author zzzyh
 * @date 2025-09-12
 */
@RestController
@RequestMapping("/systemArticle/article")
@Slf4j
public class SysArticleController extends BaseController
{
    @Autowired
    private ISysArticleService sysArticleService;

    /**
     * 查询博客文章列表
     */
    @PreAuthorize("@ss.hasPermi('systemArticle:article:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysArticle sysArticle)
    {
        startPage();
        if(sysArticle.getAuthorName() == null){

        }
        else if (!StringUtils.isEmpty(sysArticle.getAuthorName())){
            Long userIdByUserName = sysArticleService.getUserIdByUserName(sysArticle.getAuthorName());
            sysArticle.setUserId(userIdByUserName==null?-1L:userIdByUserName);
        }else {
            sysArticle.setUserId(-1L);
        }
        log.info("查询信息{}",sysArticle.toString());
        List<SysArticle> list = sysArticleService.selectSysArticleList(sysArticle);
        return getDataTable(list);
    }

    /**
     * 导出博客文章列表
     */
    @PreAuthorize("@ss.hasPermi('systemArticle:article:export')")
    @Log(title = "博客文章", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysArticle sysArticle)
    {
        List<SysArticle> list = sysArticleService.selectSysArticleList(sysArticle);
        ExcelUtil<SysArticle> util = new ExcelUtil<SysArticle>(SysArticle.class);
        util.exportExcel(response, list, "博客文章数据");
    }

    /**
     * 获取博客文章详细信息
     */
    @PreAuthorize("@ss.hasPermi('systemArticle:article:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(sysArticleService.selectSysArticleById(id));
    }

    /**
     * 新增博客文章
     */
    @PreAuthorize("@ss.hasPermi('systemArticle:article:add')")
    @Log(title = "博客文章", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysArticle sysArticle)
    {
        sysArticle.setUserId(1L);
        sysArticle.setReadType(1L);
        sysArticle.setContentMd(convertHtmlToMarkdown(sysArticle.getContent()));
        return toAjax(sysArticleService.insertSysArticle(sysArticle));
    }
    /**
     * 将HTML内容转换为Markdown格式
     * @param htmlContent HTML内容
     * @return Markdown格式内容
     */
    private String convertHtmlToMarkdown(String htmlContent) {
        if (htmlContent == null || htmlContent.isEmpty()) {
            return htmlContent;
        }

        // 简单的HTML到Markdown转换
        return htmlContent
                .replaceAll("<br\\s*/?>", "\n")
                .replaceAll("<p>", "")
                .replaceAll("</p>", "\n\n")
                .replaceAll("<strong>", "**")
                .replaceAll("</strong>", "**")
                .replaceAll("<b>", "**")
                .replaceAll("</b>", "**")
                .replaceAll("<em>", "*")
                .replaceAll("</em>", "*")
                .replaceAll("<i>", "*")
                .replaceAll("</i>", "*")
                .replaceAll("<h1>", "# ")
                .replaceAll("</h1>", "\n\n")
                .replaceAll("<h2>", "## ")
                .replaceAll("</h2>", "\n\n")
                .replaceAll("<h3>", "### ")
                .replaceAll("</h3>", "\n\n")
                .replaceAll("<[^>]*>", "") // 移除其他HTML标签
                .trim();
    }

    /**
     * 修改博客文章
     */
    @PreAuthorize("@ss.hasPermi('systemArticle:article:edit')")
    @Log(title = "博客文章", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysArticle sysArticle)
    {
        return toAjax(sysArticleService.updateSysArticle(sysArticle));
    }

    /**
     * 删除博客文章
     */
    @PreAuthorize("@ss.hasPermi('systemArticle:article:remove')")
    @Log(title = "博客文章", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(sysArticleService.deleteSysArticleByIds(ids));
    }

    //根据用户id查询作者信息
    @GetMapping("/getUserNameById/{userId}")
    public AppResult<String> getUserNameById(@PathVariable Long userId) {
        return AppResult.success("查询成功",sysArticleService.getUserNameById(userId));
    }

    @GetMapping("/getCategoryNameById/{categoryId}")
    public AppResult<String> getCategoryNameById(@PathVariable Long categoryId) {
        return AppResult.success("查询成功",sysArticleService.getCategoryNameById(categoryId));
    }

    @GetMapping("getCategoryList")
    public AppResult<List<Category>> getCategoryList() {
        return AppResult.success("查询成功",sysArticleService.getCategoryList());
    }
    @PostMapping("/upload")
    @PreAuthorize("@ss.hasPermi('systemArticle:article:add')")
    public AppResult<String> upload(@RequestParam("file") MultipartFile file) {
        log.info("上传文件: {}", file.getOriginalFilename());
        String source = "article-cover";
        try {
            // 调用上传工具方法
            String fileUrl = FileUtils.uploadUtils(file, source);
            log.info("上传成功: {}", fileUrl);
            return AppResult.success("上传成功", fileUrl);
        } catch (Exception e) {
            log.error("上传失败", e);
            return AppResult.failed("上传失败: " + e.getMessage());
        }
    }


}
